package com.sptpc.exam;

import cn.hutool.crypto.digest.DigestUtil;
import com.sptpc.exam.util.DBHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet("/admin/useradd.do")
public class UserAddServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn = null;
        try {
            conn = DBHelper.getConnection();
            String sql = "insert into user(uname, password, true_name, email, mobile, major, user_type) values(?, ?, ?, ?, ?, ?, ?)";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, request.getParameter("uname"));
            String pass = request.getParameter("password");
            String pass1 = DigestUtil.md5Hex(pass);
            pstmt.setString(2, pass1);
            pstmt.setString(3, request.getParameter("true_name"));
            pstmt.setString(4, request.getParameter("email"));
            pstmt.setString(5, request.getParameter("mobile"));
            pstmt.setString(6, request.getParameter("major"));
            pstmt.setInt(7, Integer.valueOf(request.getParameter("type")));
            pstmt.execute();

        } catch (Exception e) {
            e.printStackTrace();
        }

        response.sendRedirect("usermanage.do");
    }
}
